package com.example.testapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.testapplication.event.MessageEvent;
import com.example.testapplication.event.StickyEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class EventBusActivity extends AppCompatActivity {
    private TextView tv_title;
    private Button bt_eventbus_send;
    private Button bt_eventbus_sticky;
    private TextView tv_eventbus_result;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eventbus);

        initView(); // 初始化
        tv_title.setText("EventBus");

        initListener();  //点击事件

        // 1.注册广播
        EventBus.getDefault().register(EventBusActivity.this);

    }

    private void initListener() {
        // 跳转到发送页面
        bt_eventbus_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(EventBusActivity.this,EventBusSendActivity.class);
                startActivity(intent);

            }
        });

        // 发送粘性事件到发送页面
        bt_eventbus_sticky.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 粘性事件2.发送粘性事件
                EventBus.getDefault().postSticky(new StickyEvent("我是粘性事件"));
                Intent intent = new Intent(EventBusActivity.this,EventBusSendActivity.class);
                startActivity(intent);


            }
        });

    }
    private void initView() {
        tv_title = (TextView)findViewById(R.id.tv_title);

        bt_eventbus_send = (Button)findViewById(R.id.bt_eventbus_send);
        bt_eventbus_sticky = (Button)findViewById(R.id.bt_eventbus_sticky);
        tv_eventbus_result = (TextView)findViewById(R.id.tv_eventbus_result);
    }

    // 5.接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBut(MessageEvent event){
        // 显示接收的消息
        tv_eventbus_result.setText(event.name);
    }
/**
 * 在Activity的生命周期中，onDestory()方法是他生命的最后一步，
 * 资源空间等就被回收了。当重新进入此Activity的时候，
 * 必须重新创建，执行onCreate()方法。
 *
 * */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 2.解注册
        EventBus.getDefault().unregister(EventBusActivity.this);
    }
}
